var title = "商品";
var config = {
    url_page: _dir + "goodsManage.html",
    url_add: _dir + "goodsManage_add.html",
    title_page: title + "查询",
    title_list: title + "列表",
    title_add: "添加" + title,//商品
    title_edit: "修改" + title,//商品
    code_list: "/goods/query",//商品
    code_delete: "/goods/del",//商品
    code_add: "/goods/add",//商品
    code_edit: "/goods/update",//商品
    code_dataUpload: "/files/upload",//商品
    code_imgUpload: "/files/upload",//商品
    pagination_01: $("#page_01"),
    getQuDao: "/channel/query",
    querybuyUrls: "/goods/buyUrl/query",


    book_list: "/book/queryByGoods",//图书
    book_delete: "/book/del",//图书
    book_add: "/book/add",//图书
    book_edit: "/book/update",//图书
    book_dataUpload: "/book/coverUpload",//图书
    book_imgUpload: "/files/upload",//图书

};
$(document).ready(function () {
    if (_page == "goodsManage") {
        var pageNo = 1;
        setTitle_01(config['title_list'], config['title_page'], config['url_add']);
        //加载事件
        var _trs, _pageSize, _pageCount;
        var setData = function (pIndex, pSize) {
            pIndex = pIndex || 1;
            pSize = pSize || 20;
            var pageSetBody = { "pageNo": pIndex, "pageSize": pSize };
            var sendObj = {
                "code": $("#code").val(),
                "name": $("#name").val(),
            };
            window.sessionStorage.setItem(_page+"data",JSON.stringify({
                'sendObj':sendObj,
                'pageSetBody':pageSetBody
            }));
            $.extend(sendObj,pageSetBody);
            _call(config['code_list'], sendObj, function (res) {
                _trs = "";
                if (!res.body || res.body.length == 0) {
                    _trs = "";
                    _pageSize = 1;
                    _pageCount = 1;
                    pageNo--
                    d_alert('警告','没有更多数据啦！','warning')
                    $("#table_01 tbody").html('');
                }
                else {
                    _pageSize = res.body.pageSize;
                    _pageCount = res.body.count;
                    var goodsDescribe1=''
                    $.each(res.body, function (i, v) {
                        goodsDescribe1=v['goodsDescribe']
                        if(v['goodsDescribe'].length>0&&v['goodsDescribe'].length<20){
                            v['goodsDescribe']=v['goodsDescribe'].substring(0,20)
                        }else if(v['goodsDescribe'].length>20){
                            v['goodsDescribe']=v['goodsDescribe'].substring(0,20)+'...'
                        }
                        _trs = _trs + `<tr>
                            <td>${dataIsNull(v['id'])}</td>
                            <td>${dataIsNull(v['name'])}</td>
                            <td>${dataIsNull(v['code'])}</td>
                            <td>
                                  <textarea cols="20" rows="10" id="img" style="width: 1px;height: 1px;opacity: 0">${dataIsNull(v['imgUrl'])}</textarea>
                                    <input type="button" onClick="copyUrl2('img')" value="点击复制图片链接" />
                            </td>
                            <td>
                                <textarea cols="20" rows="10" id="video" style="width: 1px;height: 1px;opacity: 0">${dataIsNull(v['videoUrl'])}</textarea>
                                <input type="button" onClick="copyUrl2('video')" value="点击复制视频链接" />
                            </td>
                            <td style="display:none" title="${dataIsNull(goodsDescribe1)}">${dataIsNull(v['goodsDescribe'])}</td>
                            <td style="font-weight: bold">${dataIsNull(v['integral'])}</td>
                            <td>${dataIsNull(v['amount'])}</td>
                            <td>${dataIsNull(v['goodsOrder'])}</td>
                            <td>${dataIsNull(v['showType'])=='2'?'只在积分商城显示':'都显示'}</td>
                            <td>${getTdOperate('book', config['url_add'], v.id, "id", v.id,config['book_add'],config['book_list'])}</td>
                        </tr>`;
                    });
                    setPageData(res.body);
                    $("#table_01 tbody").html(_trs);
                }

                //绑定删除事件
                setDelete("id", config['code_delete']);

                //分页方法
            });
        };

        var loadingAll = function () {
            //初始化加载数据
            setData();
        }

        autoSearchByCookie(loadingAll);
        //查询方法
        loadingAll();
        $(".homePage").click(function(){
            pageNo = 1
            setData(pageNo)
        })
        $(".prevPage").click(function(){
            if(pageNo > 1){
                pageNo--
                setData(pageNo)
            }else{
                d_alert("警告",'已经到头啦！','warning')
            }
            
        })
        $(".nextPage").click(function(){
            pageNo++
            setData(pageNo)
        })

        //查询方法
        setQuery(setData)


    }
    else if (_page == "goodsManage_add") {
        var sendObj2 = {};
        var goods={}
        var editorResult=myEditor('#editor',config['code_dataUpload']);
        //初始化
        var PageInit = function () {
            var _fid = $.trim($.request.queryString["fid"]);
            var _fstaffNo = $.trim($.request.queryString["id"]);
            var _rtype = $.trim($.request.queryString["rtype"]);
            var _msgId = 0;
            this.get_fid = function () {
                return this._fid;
            };
            this.get_msgId = function () {
                return this._msgId;
            };
            this.set_fid = function (v) {
                this._fid = v;
            }
            this.set_msgId = function (v) {
                this._msgId = v;
            }
            getQuDapAjax(config['getQuDao'],'#channelId',{},function () {
                $('.select2').change()
            })
            var oldBuyUrls='';
            this.setDefault = function (v) {
                $('.addaddressBuy').click(function () {
                    var channelHtml=''
                    var html=''
                    _call(config['getQuDao'], {}, function (res) {
                        oldBuyUrl=res.body
                        $.each(res.body,function (i,v) {
                            channelHtml+=`
                               <option value="${v.id}">${v.name}</option>
                               `

                        })
                        html=`
                        <div class="row" >
                        <div class="col-sm-5">

                        <label class='control-label valited-required form-group' for="channelId">渠道名</label>
                        <div>
                        <select  class="form-control form-group" style="height: 34px;line-height: 34px" >
                               ${channelHtml}
                        </select>
                        </div>
                        </div>
                        <div class="col-sm-7 addressWrapper ">
                        <label  class="control-label valited-required form-group">购买地址:</label>
                        <div style="display: flex;justify-content: space-between">
                        <input type="text" placeholder="请输入购买地址"   class="form-control form-group" style="width: 70%"/>
                        <b style="cursor:pointer" class="deleteInput">❌</b>
                        </div>
                        </div>

                        </div>
                        `
                        $('#formAdd').append(html)
                    })
                })
                $('body').on('click','.addressBuy',function () {
                    $('#buyUrlModel').modal()
                })
                $('#submitJifen').click(function () {
                    //var arrResult=[]
                    //var aText=$('#formAdd .row')
                    //$.each(aText,function (i,v) {
                    //    arrResult.push({
                    //        channelId:$(v).find('select').val(),
                    //        buyUrl:$(v).find('input').val(),
                    //    })
                    //})
                    //sendObj2["buyUrls"]= JSON.stringify(arrResult)
                    $('#buyUrlModel').modal('hide')
                })
                //$('#cancelJifen').click(function () {
                //    console.log(oldBuyUrls)
                //    //var arrResult=[]
                //    //var aText=$('#formAdd .row')
                //    //$.each(aText,function (i,v) {
                //    //    arrResult.push({
                //    //        channelId:$(v).find('select').val(),
                //    //        buyUrl:$(v).find('input').val(),
                //    //    })
                //    //})
                //    //sendObj2["buyUrls"]= JSON.stringify(arrResult)
                //    $('#buyUrlModel').modal('hide')
                //})
                $('#formAdd').on('click','.deleteInput',function () {
                    if($(this).parents('#formAdd').find('.row').length>=2){
                        $(this).parents('.row').remove()
                    }else{
                        alert('添加框小于2，不能删除')
                    }
                })
                var html=''
                _call(config['getQuDao'], {}, function (resQudao) {
                     _call(config['querybuyUrls'],{id:_v.id},function (res) {
                    if(res.body){
                        $.each(res.body,function (i,v) {
                            html+=`
                                    <div class="row" >
                                    <div class="col-sm-5">
            
                                    <label class='control-label valited-required form-group' for="channelId">渠道名</label>
                                    <div>
                                    <select value="${v.channelId}" class="form-control form-group" style="height: 34px;line-height: 34px" >
                                           ${getQudaofun(resQudao.body,v.channelId)}
                                    </select>
                                    </div>
                                    </div>
                                    <div class="col-sm-7 addressWrapper ">
                                    <label  class="control-label valited-required form-group">购买地址:</label>
                                    <div style="display: flex;justify-content: space-between">
                                    <input type="text" placeholder="请输入购买地址"  value="${v.buyUrl}"  class="form-control form-group" style="width: 70%"/>
                                    <b style="cursor:pointer" class="deleteInput">❌</b>
                                    </div>
                                    </div>
            
                                    </div>
                                    `

                        })
                        $('#formAdd').html(html)
                    }
                    var aText=$('#formAdd .row')
                    if(aText.length>0&&aText.find('input').val()){
                        var arrResult=[]
                        $.each(aText,function (i,v) {
                            arrResult.push({
                                channelId:$(v).find('select').val(),
                                buyUrl:$(v).find('input').val(),
                            })
                        })
                    //    sendObj2["buyUrls"]= JSON.stringify(arrResult)
                    }
                     })
                })

                if (_fid == "" && _fstaffNo == "" && _rtype == "") {
                    //添加
                    sendObj2={};
                    this.set_msgId(config['code_add']);
                    this.set_fid(0);
                    setTitle_02(config['title_add'],config['url_page']);
                    new setUpload($("#idCardParent"),{'uploadUrl':config['code_dataUpload'],"urlDom":$("#imgUrl"),'title':"商品图片"});
                    new setUpload($("#businessParent"),{'uploadUrl':config['code_dataUpload'],"urlDom":$("#videoUrl"),'title':"商品视频"});
                }
                else if (_fid != "" && _fstaffNo != "" && _rtype == "edit") {
                    //修改
                    goods['id']=_fid
                    function getQudaofun(defaultValue,id) {
                        var channelHtml=''
                        $.each(defaultValue, function (i, v) {
                            channelHtml += `
                               <option ${v.id==id?'selected':''} value="${v.id}">${v.name}</option>
                               `
                        })
                        return channelHtml
                    }
                    this.set_msgId(config['code_edit']);
                    this.set_fid(_fid);
                    setTitle_02(config['title_edit'],config['url_page']);
                    if (getPageData(_fstaffNo)) {
                        var _v = getPageData(_fstaffNo);
                        var formObj = new Form();
                        formObj.init(_v);
                          editorResult.txt.html(_v.content)
                        $('#describe').val(_v.goodsDescribe)
                        $('#order').val(_v.goodsOrder)
                        $('#describe').val(_v.goodsDescribe)
                        new setUpload($("#idCardParent"),{'uploadUrl':config['code_dataUpload'],"urlDom":$("#imgUrl")});
                        new setUpload($("#businessParent"),{'uploadUrl':config['code_dataUpload'],"urlDom":$("#videoUrl")});



                    }
                }

            }
        };

        var _default = new PageInit();
        _default.setDefault();

        //提交事件
        $(".validate-form .submit").on("click", function () {
            var _this = $(this);

            var arrResult=[]
            var aText=$('#formAdd .row')
            $.each(aText,function (i,v) {
                arrResult.push({
                    channelId:$(v).find('select').val(),
                    buyUrl:$(v).find('input').val(),
                })
            })

            sendObj2["buyUrls"]= JSON.stringify(arrResult)

            if($('#formAdd .row').find('input').val()){
                if ($(".validate-form").validate().form()) {
                    sendObj2["goods"]=JSON.stringify(
                        Object.assign({
                            name : $("#name").val(),
                            code : $("#code").val(),
                            imgUrl : $("#imgUrl").val(),
                            videoUrl : $("#videoUrl").val(),
                            goodsDescribe : $("#goodsDescribe").val(),
                            content : editorResult.txt.html(),
                            integral : $("#integral").val(),
                            amount : $("#amount").val(),
                            goodsOrder : $("#goodsOrder").val(),
                            showType : $("#showType").val(),

                        },goods)
                    )

                    sendObj2["goods"]= encodeURIComponent(sendObj2["goods"])
                    sendObj2["buyUrls"]=encodeURIComponent(sendObj2["buyUrls"])
                    _call(_default.get_msgId(), sendObj2, function (res) {
                        confirm_add_ok(res, config['url_page'], function () {
                            window.location.href = window.location.href;
                        });
                    });

                }
            }else{
                alert('请选择购买地址')
            }

        });
    }
    if($(".select2").length>0){
        $(".select2").select2();
    }

});